package com.niit.agricstore.controller;

import com.niit.agricstore.entity.Address;
import com.niit.agricstore.service.AddressService;
import com.niit.agricstore.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    AddressService addressService;

    public AddressController(AddressService addressService) {
        this.addressService = addressService;
    }

    @PostMapping("/addresses")
    public Result<Void> addAddress(@RequestBody Address address) {
        addressService.addAddress(address);
        return Result.success();
    }

    @PutMapping("/addresses/{addressId}")
    public Result updateAddress(@PathVariable int addressId, @RequestBody Address address) {
        address.setAddressAid(addressId);
        addressService.updateAddress(address);
        return Result.success();
    }

    @DeleteMapping("/addresses/{addressId}")
    public Result deleteAddress(@PathVariable int addressId) {
        addressService.deleteAddress(addressId);
        return Result.success();
    }

    @GetMapping("/users/{userId}/addresses")
    public Result<List<Address>> getAddressListByUserId(@PathVariable long userId) {
        List<Address> addressList = addressService.getAddressListByUserId(userId);
        return Result.success(addressList);
    }

    @GetMapping("/users/{userId}/addresses/default")
    public Result<Address> getDefaultAddressByUserId(@PathVariable long userId) {
        Address defaultAddress = addressService.getDefaultAddressByUserId(userId);
        return Result.success(defaultAddress);
    }

    @GetMapping("/addresses/{addressId}")
    public Result<Address> getAddressById(@PathVariable int addressId) {
        Address address = addressService.getAddressById(addressId);
        return Result.success(address);
    }

    @GetMapping("/addresses/search")
    public Result<List<Address>> searchAddressByKeyword(@RequestParam String keyword) {
        List<Address> addressList = addressService.searchAddressByKeyword(keyword);
        return Result.success(addressList);
    }

    @PostMapping("/users/{userId}/addresses/{addressId}/default")
    public Result setDefaultAddress(@PathVariable long userId, @PathVariable int addressId) {
        addressService.setDefaultAddress(userId, addressId);
        return Result.success();
    }
}